package android.mcsmtms.manager;

import java.util.LinkedList;

import android.location.Location;

public class SpeedManager {
	private LinkedList<Location> trackLocationList;
	private final int size = 10;	
	
	public SpeedManager() {
		super();
		
		trackLocationList = new LinkedList<Location>();
	}
	
	public void addLocation(Location currentLocation) {
		trackLocationList.add(currentLocation);
		if(trackLocationList.size() >= size)
			trackLocationList.removeFirst();
	}
	
	public double getAverageSpeed() {
//		double sumSpeed = 0;
//		for(int i=0; i<speedArray.length; i++) {
//			sumSpeed += speedArray[i];
//		}
//		
//		double averageSpeed = sumSpeed / (speedArray.length * 1.0);
//		return averageSpeed;
		int numSpeed = 0;
		double sumSpeed = 0;
		for(Location loc : trackLocationList) {
			if(loc==null) continue;
			if(loc.hasSpeed()) {
				sumSpeed += loc.getSpeed();
				numSpeed++;
			}
		}
		
		double averageSpeed = sumSpeed / (numSpeed * 1.0);
		return averageSpeed;
	}
	
	public double computeCurrentSpeed() { // in meters/second
		int currentListSize = trackLocationList.size();
		if(currentListSize < 2)
			return 0;
		
		Location currentLocation = trackLocationList.get(currentListSize-1);
		Location lastLocation = trackLocationList.get(currentListSize-2);
		
		if(lastLocation == null || currentLocation == null)
			return 0;
		
		float distance = currentLocation.distanceTo(lastLocation);
		long time = currentLocation.getTime() - lastLocation.getTime();
		
		double speed = distance / (time * (1000 * 1.0));
		
		return speed;
	}
	
	public int getLocationListSize() {
		return trackLocationList.size();
	}
	
	public double getSumSpeed() {
		double sumSpeed = 0;
		for(Location loc : trackLocationList) {
			if(loc==null) continue;
			if(loc.hasSpeed()) {
				sumSpeed += loc.getSpeed();
			}
		}
		return sumSpeed;
	}
}
